<template>
  <div class="api-example">
    <h2>自动生成的API使用示例</h2>
    
    <!-- 参数模型管理 -->
    <div class="section">
      <h3>参数模型管理</h3>
      <div class="test-data-generator" style="margin-bottom: 15px;">
        <label>测试场景：</label>
        <select v-model="currentScenario" style="margin-right: 10px; padding: 5px;">
          <option v-for="scenario in testScenarios" :key="scenario.value" :value="scenario.value">
            {{ scenario.label }}
          </option>
        </select>
        <button @click="generateNewTestData" :disabled="loading" style="background-color: #52c41a; color: white;">
          生成测试数据
        </button>
      </div>
      <div class="button-group">
        <button @click="buildModel" :disabled="loading">
          {{ loading ? '处理中...' : '建立参数模型' }}
        </button>
        <button @click="validateDataLocal" :disabled="loading">
          验证数据
        </button>
        <button @click="getAdapterList" :disabled="loading">
          获取适配器列表
        </button>
      </div>
    </div>

    <!-- APS算法编排 -->
    <div class="section">
      <h3>APS算法编排</h3>
      <div class="button-group">
        <button @click="executeSchedule" :disabled="loading || !model">
          执行自动排程
        </button>
        <button @click="executeScheduleWithAlgorithm" :disabled="loading || !model">
          执行SPT算法排程
        </button>
        <button @click="checkHealth" :disabled="loading">
          健康检查
        </button>
      </div>
    </div>

    <!-- 当前测试数据 -->
    <div class="section">
      <h3>当前测试数据</h3>
      <div class="test-data-display">
        <pre>{{ sampleJsonData }}</pre>
      </div>
    </div>

    <!-- 结果显示 -->
    <div class="section" v-if="result">
      <h3>执行结果</h3>
      <div class="result-display">
        <pre>{{ JSON.stringify(result, null, 2) }}</pre>
      </div>
    </div>

    <!-- 错误显示 -->
    <div class="section" v-if="error">
      <h3>错误信息</h3>
      <div class="error-display">
        <pre>{{ error }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'

// 导入自动生成的API函数
import { 
  buildFromJson, 
  validateData, 
  getAdapters,
  schedule,
  scheduleWithAlgorithm,
  health,
  generateTestData
} from '@/api/generated'

// 导入自动生成的类型定义
import type { 
  APSProductModel, 
  SchedulingRequest,
  SchedulingResult,
  HealthStatus,
  Result 
} from '@/api/generated'

// 响应式数据
const loading = ref(false)
const result = ref<any>(null)
const error = ref<string>('')
const model = ref<APSProductModel | null>(null)
const currentScenario = ref<string>('basic')

// 测试场景选项
const testScenarios = [
  { value: 'basic', label: '基础场景' },
  { value: 'small', label: '小规模场景' },
  { value: 'medium', label: '中等规模场景' },
  { value: 'large', label: '大规模场景' },
  { value: 'urgent', label: '紧急交期场景' },
  { value: 'resource_constrained', label: '资源紧张场景' },
  { value: 'complex', label: '复杂工艺场景' }
]

// 生成测试数据
const generateNewTestData = async () => {
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const response = await generateTestData({ arg0: currentScenario.value })
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('测试数据生成成功！')
    
    // 更新示例数据
    sampleJsonData.value = JSON.stringify(response, null, 2)
    
  } catch (err: any) {
    error.value = err.message || '测试数据生成失败'
    message.error('测试数据生成失败')
  } finally {
    loading.value = false
  }
}

// 示例JSON数据 - 符合后端ProductionData模型要求
const sampleJsonData = ref(JSON.stringify({
  productInfo: {
    productId: 'PROD-001',
    productName: '汽车齿轮',
    productCategory: '传动部件',
    material: '合金钢',
    specifications: {
      outerDiameter: {
        value: 100.0,
        unit: 'mm',
        tolerance: '±0.1'
      },
      height: {
        value: 20.0,
        unit: 'mm',
        tolerance: '±0.05'
      },
      weight: {
        value: 0.5,
        unit: 'kg',
        tolerance: '±0.01'
      }
    },
    annualDemand: 10000,
    description: '高精度汽车齿轮，模数3，齿数24，压力角20°'
  },
  orders: [
    {
      orderId: 'ORD-001',
      customerName: '大众汽车',
      customerLevel: 'A',
      productModel: 'GEAR-001',
      quantity: 1000,
      deliveryDate: '2024-12-31',
      priority: '高',
      orderAmount: 500000.00
    }
  ],
  processFlow: [
    {
      operationId: 'STEP-001',
      operationName: '车削加工',
      sequence: 1,
      equipmentType: '车床',
      standardTime: {
        value: 30.0,
        unit: '分钟'
      },
      setupTime: {
        value: 15.0,
        unit: '分钟'
      },
      personnelRequirement: '中级车工',
      qualityRequirement: '表面粗糙度Ra1.6'
    },
    {
      operationId: 'STEP-002',
      operationName: '齿轮加工',
      sequence: 2,
      equipmentType: '滚齿机',
      standardTime: {
        value: 45.0,
        unit: '分钟'
      },
      setupTime: {
        value: 20.0,
        unit: '分钟'
      },
      personnelRequirement: '高级技工',
      qualityRequirement: '齿轮精度7级'
    },
    {
      operationId: 'STEP-003',
      operationName: '热处理',
      sequence: 3,
      equipmentType: '热处理炉',
      standardTime: {
        value: 120.0,
        unit: '分钟'
      },
      setupTime: {
        value: 30.0,
        unit: '分钟'
      },
      personnelRequirement: '热处理技师',
      qualityRequirement: '硬度HRC45-50'
    }
  ],
  equipment: [
    {
      equipmentId: 'EQ-001',
      equipmentName: '数控车床',
      equipmentType: '车床',
      dailyCapacity: {
        value: 480.0,
        unit: '分钟'
      },
      efficiencyFactor: 0.95,
      maintenanceSchedule: '每周维护',
      status: '正常'
    },
    {
      equipmentId: 'EQ-002',
      equipmentName: '数控滚齿机',
      equipmentType: '滚齿机',
      dailyCapacity: {
        value: 480.0,
        unit: '分钟'
      },
      efficiencyFactor: 0.90,
      maintenanceSchedule: '每月维护',
      status: '正常'
    },
    {
      equipmentId: 'EQ-003',
      equipmentName: '热处理炉',
      equipmentType: '热处理设备',
      dailyCapacity: {
        value: 480.0,
        unit: '分钟'
      },
      efficiencyFactor: 0.85,
      maintenanceSchedule: '每季度维护',
      status: '正常'
    }
  ],
  personnel: [
    {
      personnelId: 'PER-001',
      name: '张三',
      jobType: '车工',
      skillLevel: '中级',
      dailyWorkHours: {
        value: 8.0,
        unit: '小时'
      },
      operableEquipment: ['EQ-001'],
      status: '在岗'
    },
    {
      personnelId: 'PER-002',
      name: '李四',
      jobType: '齿轮工',
      skillLevel: '高级',
      dailyWorkHours: {
        value: 8.0,
        unit: '小时'
      },
      operableEquipment: ['EQ-002'],
      status: '在岗'
    },
    {
      personnelId: 'PER-003',
      name: '王五',
      jobType: '热处理工',
      skillLevel: '高级',
      dailyWorkHours: {
        value: 8.0,
        unit: '小时'
      },
      operableEquipment: ['EQ-003'],
      status: '在岗'
    }
  ],
  constraints: {
    hardConstraints: [
      {
        constraintId: 'HC-001',
        constraintType: '交期约束',
        description: '订单必须在交付日期前完成',
        priority: '高'
      }
    ],
    softConstraints: [
      {
        constraintId: 'SC-001',
        constraintType: '成本优化约束',
        description: '总成本不能超过预算',
        weight: 0.7
      }
    ]
  }
}))

// 建立参数模型
const buildModel = async () => {
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    console.log('开始建立参数模型...')
    console.log('发送数据:', sampleJsonData.value)
    
    const response = await buildFromJson(
      sampleJsonData.value,
      { arg1: 'automotive' }
    )
    
    console.log('API响应:', response)
    
    // kubb已自动提取data字段，response就是data内容
    model.value = response as APSProductModel
    result.value = response
    message.success('参数模型建立成功！')
    
    console.log('结果已设置:', result.value)
  } catch (err: any) {
    console.error('API调用失败:', err)
    error.value = err.message || '模型建立失败'
    message.error('模型建立失败')
  } finally {
    loading.value = false
  }
}

// 验证数据
const validateDataLocal = async () => {
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const response = await validateData(sampleJsonData.value)
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('数据验证完成！')
  } catch (err: any) {
    error.value = err.message || '数据验证失败'
    message.error('数据验证失败')
  } finally {
    loading.value = false
  }
}

// 获取适配器列表
const getAdapterList = async () => {
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const response = await getAdapters()
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('适配器列表获取成功！')
  } catch (err: any) {
    error.value = err.message || '获取适配器失败'
    message.error('获取适配器失败')
  } finally {
    loading.value = false
  }
}

// 执行自动排程
const executeSchedule = async () => {
  if (!model.value) {
    message.warning('请先建立参数模型')
    return
  }
  
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const request: SchedulingRequest = {
      model: model.value,
      parameters: {
        maxExecutionTime: 30000,
        enableDetailedLogging: true,
        randomSeed: 12345
      }
    }
    
    const response = await schedule(request)
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('自动排程执行成功！')
  } catch (err: any) {
    error.value = err.message || '排程执行失败'
    message.error('排程执行失败')
  } finally {
    loading.value = false
  }
}

// 执行指定算法排程
const executeScheduleWithAlgorithm = async () => {
  if (!model.value) {
    message.warning('请先建立参数模型')
    return
  }
  
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const request: SchedulingRequest = {
      model: model.value,
      parameters: {
        maxExecutionTime: 30000,
        enableDetailedLogging: true,
        randomSeed: 12345
      }
    }
    
    const response = await scheduleWithAlgorithm('SPT', request)
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('SPT算法排程执行成功！')
  } catch (err: any) {
    error.value = err.message || '算法排程执行失败'
    message.error('算法排程执行失败')
  } finally {
    loading.value = false
  }
}

// 健康检查
const checkHealth = async () => {
  loading.value = true
  error.value = ''
  result.value = null
  
  try {
    const response = await health()
    
    // kubb已自动提取data字段，response就是data内容
    result.value = response
    message.success('健康检查完成！')
  } catch (err: any) {
    error.value = err.message || '健康检查失败'
    message.error('健康检查失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.api-example {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background-color: #fafafa;
}

.section h3 {
  margin-top: 0;
  color: #1890ff;
  border-bottom: 2px solid #1890ff;
  padding-bottom: 10px;
}

.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.button-group button {
  padding: 8px 16px;
  border: 1px solid #1890ff;
  background-color: #fff;
  color: #1890ff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.button-group button:hover:not(:disabled) {
  background-color: #1890ff;
  color: #fff;
}

.button-group button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.result-display,
.error-display {
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.result-display pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
}

.error-display {
  background-color: #fff2f0;
  border-color: #ffccc7;
}

.error-display pre {
  color: #ff4d4f;
}
</style>
